package cn.com.ghy.android.widget.report;

import java.io.Serializable;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Calendar;
import java.util.Date;
import java.util.List;

import android.app.Activity;
import android.app.AlertDialog;
import android.app.DatePickerDialog;
import android.app.DatePickerDialog.OnDateSetListener;
import android.app.Dialog;
import android.app.ProgressDialog;
import android.content.Intent;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.view.View;
import android.widget.AdapterView;
import android.widget.AdapterView.OnItemSelectedListener;
import android.widget.ArrayAdapter;
import android.widget.Button;
import android.widget.DatePicker;
import android.widget.EditText;
import android.widget.Spinner;
import android.widget.Toast;
import cn.com.ghy.android.bean.LoginInfoBean;
import cn.com.ghy.android.bean.OrderReportInfoBean;
import cn.com.ghy.android.bean.OrderStatusBean;
import cn.com.ghy.android.exception.DisposeException;
import cn.com.ghy.android.service.OrderOpeService;
import cn.com.ghy.android.util.CommonStatic;
import cn.com.ghy.android.widget.ComStaticApp;
import cn.com.ghy.android.widget.R;

/**
 * @软件著作权:金红叶纸业集团有限公司
 * @系统名称:SFA系统
 * @Description:订单报表查询
 * @author wuz  @date 2011-5-19 08:56:00
 * @版本历史:v1.0
 * @Copyright:Copyright (c) 2011-2012 
 */

public class OrderReportQuery extends Activity {

	private EditText txtAdviceOrderId = null;
	private EditText txtHandOrderId = null;
	private EditText txtCustomerId = null;
	private EditText txtCustomerName = null;
	private Button btnOrderStartDate = null;
	private Button btnOrderEndDate = null;
	private Button btnOrderListQuery = null;
	private Spinner spiOrderStatus = null;
	private ProgressDialog progressDialog = null;

	private int mYear = 0, mMonth = 0, mDay = 0;

	private String adviceOrderId = null;
	private String handOrderId = null;
	private String customerId = null;
	private String customerName = null;
	private String orderStartDate = null;
	private String orderEndDate = null;

	private OrderReportInfoBean orderReportInfoBean = null;
	private LoginInfoBean loginInfoBean = null;

	private Intent intent = null;
	private Bundle bundle = null;
	private HttpThread thread = null;

	String monthStr = "";
	String dayStr = "";

	private DisposeException disposeException = null;

	@Override
	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		this.setContentView(R.layout.order_report_query);
		getSession();
		findView();
		init();
		setListener();
	}

	public void getSession() {
		disposeException = ((ComStaticApp) getApplication()).getDisposeException();
		loginInfoBean = ((ComStaticApp) this.getApplication()).getLoginInfo();
	}

	private void findView() {
		txtAdviceOrderId = (EditText) this.findViewById(R.id.txtAdviceOrderId);
		txtHandOrderId = (EditText) this.findViewById(R.id.txtHandOrderId);
		txtCustomerId = (EditText) this.findViewById(R.id.txtCustomerId);
		txtCustomerName = (EditText) this.findViewById(R.id.txtCustomerName);

		btnOrderStartDate = (Button) this.findViewById(R.id.btnOrderStartDate);
		btnOrderEndDate = (Button) this.findViewById(R.id.btnOrderEndDate);
		btnOrderListQuery = (Button) this.findViewById(R.id.btnOrderListQuery);

		spiOrderStatus = (Spinner) this.findViewById(R.id.spiOrderStatus);
	}

	private void init() {
		orderReportInfoBean = new OrderReportInfoBean();
		final Calendar c = Calendar.getInstance();
		mYear = c.get(Calendar.YEAR);
		mMonth = c.get(Calendar.MONTH);
		mDay = c.get(Calendar.DAY_OF_MONTH);
		if ((mMonth + 1) < 10) {
			monthStr = "0" + (mMonth + 1);
		} else {
			monthStr = (mMonth + 1) + "";
		}
		if (mDay < 10) {
			dayStr = "0" + mDay;
		} else {
			dayStr = mDay + "";
		}
		btnOrderStartDate.setText(mYear + "-" + monthStr + "-" + dayStr);
		btnOrderEndDate.setText(mYear + "-" + monthStr + "-" + dayStr);

		mYear = c.get(Calendar.YEAR);
		mMonth = c.get(Calendar.MONTH);
		mDay = c.get(Calendar.DAY_OF_MONTH);

		List<OrderStatusBean> list = new ArrayList<OrderStatusBean>();
		list.add(new OrderStatusBean(getResources().getString(R.string.unauditId), getResources()
				.getString(R.string.unaudit)));
		list.add(new OrderStatusBean(getResources().getString(R.string.auditedId), getResources()
				.getString(R.string.audited)));
		list.add(new OrderStatusBean(getResources().getString(R.string.sendedGoodsId),
				getResources().getString(R.string.sendedGoods)));
		list.add(new OrderStatusBean(getResources().getString(R.string.canceledId), getResources()
				.getString(R.string.canceled)));
		list.add(new OrderStatusBean(getResources().getString(R.string.allId), getResources()
				.getString(R.string.all)));
		ArrayAdapter<OrderStatusBean> adapter = new ArrayAdapter<OrderStatusBean>(
				OrderReportQuery.this, android.R.layout.simple_spinner_item, list);
		adapter.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);
		spiOrderStatus.setAdapter(adapter);
	}

	private OnDateSetListener orderStartDateLis = new DatePickerDialog.OnDateSetListener() {
		public void onDateSet(DatePicker view, int year, int monthOfYear, int dayOfMonth) {
			mYear = year;
			mMonth = monthOfYear;
			if (mMonth + 1 < 10) {
				monthStr = "0" + (mMonth + 1);
			} else {
				monthStr = (mMonth + 1) + "";
			}
			mDay = dayOfMonth;
			if (mDay < 10) {
				dayStr = "0" + mDay;
			} else {
				dayStr = mDay + "";
			}
			btnOrderStartDate.setText(mYear + "-" + monthStr + "-" + dayStr);
		}
	};

	private OnDateSetListener orderEndDateLis = new DatePickerDialog.OnDateSetListener() {
		public void onDateSet(DatePicker view, int year, int monthOfYear, int dayOfMonth) {
			mYear = year;
			mMonth = monthOfYear;
			if (mMonth + 1 < 10) {
				monthStr = "0" + (mMonth + 1);
			} else {
				monthStr = (mMonth + 1) + "";
			}
			mDay = dayOfMonth;
			if (mDay < 10) {
				dayStr = "0" + mDay;
			} else {
				dayStr = mDay + "";
			}
			btnOrderEndDate.setText(mYear + "-" + monthStr + "-" + dayStr);
		}
	};

	private OnItemSelectedListener spiSelectListener = new OnItemSelectedListener() {
		public void onItemSelected(AdapterView<?> parent, View view, int position, long id) {
			orderReportInfoBean.setOrderstate((OrderStatusBean) parent.getItemAtPosition(position));
		}

		public void onNothingSelected(AdapterView<?> parent) {

		}

	};

	@Override
	protected Dialog onCreateDialog(int id) {
		switch (id) {
			case R.id.btnOrderStartDate :
				return new DatePickerDialog(this, orderStartDateLis, mYear, mMonth, mDay);
			case R.id.btnOrderEndDate :
				return new DatePickerDialog(this, orderEndDateLis, mYear, mMonth, mDay);
		}
		return null;
	}

	private void setListener() {
		btnOrderStartDate.setOnClickListener(btnListenerEvent);
		btnOrderEndDate.setOnClickListener(btnListenerEvent);
		btnOrderListQuery.setOnClickListener(btnListenerEvent);
		spiOrderStatus.setOnItemSelectedListener(spiSelectListener);
	}

	private View.OnClickListener btnListenerEvent = new View.OnClickListener() {

		public void onClick(View v) {
			Button button = (Button) v;
			switch (button.getId()) {
				case R.id.btnOrderStartDate :
					showDialog(R.id.btnOrderStartDate);
					break;
				case R.id.btnOrderEndDate :
					showDialog(R.id.btnOrderEndDate);
					break;
				case R.id.btnOrderListQuery :
					getViewValue();
					boolean flag = false;
					try {
						flag = checkDate(orderStartDate, orderEndDate);
					} catch (Exception e) {
						Toast.makeText(OrderReportQuery.this, "系统错误,请联系管理员!", Toast.LENGTH_SHORT)
								.show();
						return;
					}
					if (!flag) {
						return;
					}

					orderReportInfoBean.setOrderid(adviceOrderId);
					orderReportInfoBean.setOrderno(handOrderId);
					orderReportInfoBean.setPartner(customerId);
					orderReportInfoBean.setCustname(customerName);
					orderReportInfoBean.setCrbegindate(orderStartDate);
					orderReportInfoBean.setCrenddate(orderEndDate);
					thread = new HttpThread(handler);
					thread.doStart();
					break;
			}
		}
	};

	private void getViewValue() {
		adviceOrderId = txtAdviceOrderId.getText().toString().trim();
		handOrderId = txtHandOrderId.getText().toString().trim();
		customerId = txtCustomerId.getText().toString().trim();
		customerName = txtCustomerName.getText().toString().trim();
		orderStartDate = btnOrderStartDate.getText().toString().trim() + " 00:00:00";
		orderEndDate = btnOrderEndDate.getText().toString().trim() + " 23:59:59";
	}

	private boolean checkDate(String startDateStr, String endDateStr) throws Exception {
		SimpleDateFormat format = new SimpleDateFormat("yyyy-MM-dd hh:mm:ss");
		Date startDate = format.parse(startDateStr);
		Date endDate = format.parse(endDateStr);
		int result = startDate.compareTo(endDate);
		if (result == 1) {
			Toast.makeText(OrderReportQuery.this, "开始日期必须小于结束日期!", Toast.LENGTH_SHORT).show();
			return false;
		} else if (result == 0) {
			Toast.makeText(OrderReportQuery.this, "开始日期不能等于结束日期!", Toast.LENGTH_SHORT).show();
			return false;
		}
		if (!startDateStr.substring(0, 7).equals(endDateStr.substring(0, 7))) {
			Toast.makeText(OrderReportQuery.this, "查询日期范围不可以跨月!", Toast.LENGTH_SHORT).show();
			return false;
		}
		return true;
	}

	private class HttpThread extends Thread {
		private Handler handle = null;

		public HttpThread(Handler hander) {
			handle = hander;
		}

		public void doStart() {
			progressDialog = new ProgressDialog(OrderReportQuery.this);
			progressDialog.setTitle("提示信息");
			progressDialog.setMessage("正在请求数据，请稍等......");
			progressDialog.setCancelable(false);
			progressDialog.show();
			this.start();
		}

		public void run() {
			Message message = null;
			try {
				List<OrderReportInfoBean> list = null;
				OrderOpeService orderOpeService = new OrderOpeService();
				list = orderOpeService.GetOrderList(orderReportInfoBean, loginInfoBean);
				if (list.size() > 0) {
					progressDialog.dismiss();
					message = handle.obtainMessage();
					bundle = new Bundle();
					message.what = CommonStatic.STATE_NORMAL;
					bundle.putSerializable("list", (Serializable) list);
					message.setData(bundle);
					handle.sendMessage(message);
				} else {
					progressDialog.dismiss();
					message = handle.obtainMessage();
					message.what = CommonStatic.STATE_NORMAL_NULL;
					handle.sendMessage(message);
				}
			} catch (Exception ex) {
				progressDialog.dismiss();
				disposeException.handleException(ex);
			}
		}
	}

	private Handler handler = new Handler() {
		@SuppressWarnings("unchecked")
		public void handleMessage(Message m) {
			switch (m.what) {
				case CommonStatic.STATE_NORMAL :
					List<OrderReportInfoBean> list = (List<OrderReportInfoBean>) m.getData()
							.getSerializable("list");
					bundle = new Bundle();
					bundle.putSerializable("orderReportInfolist", (Serializable) list);
					intent = new Intent(OrderReportQuery.this, OrderReportList.class);
					intent.putExtras(bundle);
					OrderReportQuery.this.startActivity(intent);
					break;
				case CommonStatic.STATE_NORMAL_NULL :
					new AlertDialog.Builder(OrderReportQuery.this).setTitle("提示信息")
							.setMessage("该条件,暂时没有订单信息!").setNeutralButton("关闭", null).show();
					break;
			}
		}
	};
}
